package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置类
 *
 * @auth shanyue
 * @date 2025年08月06日11:38
 */
@Configuration
public class RedisConfiguration {

    /**
     * 配置RedisTemplate，用于操作redis中的key-value数据
     * key:String
     * value:Object
     *
     * @param factory Redis连接工厂
     * @return RedisTemplate<String, Object>
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //创建RedisTemplate实例
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //设置连接工厂
        template.setConnectionFactory(factory);

        //设置value的序列化方式为Jackson
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        template.setValueSerializer(serializer);
        //设置key的序列化方式为String
        template.setKeySerializer(new StringRedisSerializer());

        //初始化配置
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 配置StringRedisTemplate，用于操作String类型的key-value数据
     *
     * @param factory 连接工厂
     * @return StringRedisTemplate
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        return new StringRedisTemplate(factory);
    }

}
